package com.gzsxy.esjy.service.netty.handler;

import cn.hutool.core.util.URLUtil;

import com.gzsxy.esjy.common.Assert;
import com.gzsxy.esjy.request.impl.FileHttpServletRequest;
import com.gzsxy.esjy.service.netty.decoder.FilePathParser;
import com.gzsxy.esjy.service.netty.fileServer.configure.ServerStaticProperties;
import com.gzsxy.esjy.service.netty.service.FileDownLoadService;
import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * <p>
 * 绝对路径文件处理,不进行hash code 计算路径
 * </p>
 *
 * @author zhangxiaolong
 * @date 2022/7/11 9:36
 */
public class AbsolutePathFileDownloadHandler extends FileDownloadHandler {

    public AbsolutePathFileDownloadHandler(FileDownLoadService pool) {
        super(pool);
    }

    @Override
    public FilePathParser parseParam(FileHttpServletRequest request) {
        try {
            String uri = request.getUri();
            uri = URLUtil.decode(uri, request.getCharset());

            //去除前缀
            uri = uri.replaceFirst(ServerStaticProperties.ABSOLUTE_RESOURCES_PREFIX, "");
            //435c4f605b1847898380290507189009/2010/12/08/cec412b5cbe8498ebc5290fb155e714b/60/80.jpg
            FilePathParser filePath = new FilePathParser();

            int index = uri.indexOf("/", 1);
            filePath.setSystemId(uri.substring(1, index));
            uri = uri.substring(index + 1);
            int lastIndex = uri.lastIndexOf("/");
            String baseDir = "";
            String fileName = null;
            if (lastIndex > 0) {
                baseDir = uri.substring(0, lastIndex + 1);
                fileName = uri.substring(lastIndex + 1);
            } else {
                fileName = uri;
            }
            filePath.setOriDirectIndex(getFilePath(baseDir, fileName));
            filePath.createDirectIndex();
            return filePath;
        } catch (Exception e) {
            Assert.isNotNull(null, e.getMessage(), HttpResponseStatus.BAD_REQUEST.code(), e);
        }
        return null;
    }

    public static String getFilePath(String baseDir, String fileName) {
        if (baseDir == null) {
            baseDir = "";
        } else {
            if (!baseDir.endsWith("/")) {
                baseDir += "/";
            }
            if (baseDir.startsWith("/")) {
                baseDir = baseDir.substring(1);
            }
        }

        return baseDir + fileName;
    }
}
